import React, { useEffect } from "react";
import styles from './SearchPage.module.css'
import { Header, Footer, FilterArea, ProductList } from "../../components";
import { useSelector } from "../../redux/hooks";
import { searchProduct } from "../../redux/productSearch/slice";
// import { Dispatch } from "@reduxjs/toolkit";
import { useParams, useLocation } from "react-router-dom";
import { Spin } from "antd";
import { useDispatch } from "react-redux"

interface MatchParams {
    keywords: string
}



export const SearchPage: React.FC = () => {
    const { keywords } = useParams<MatchParams>()
    const loading = useSelector((state) => state.productSearch.loading)
    const error = useSelector(s => s.productSearch.error)
    const data = useSelector(s => s.productSearch.data)
    const paging = useSelector(s => s.productSearch.pagination)
    const location = useLocation()
    const dispatch = useDispatch()

    useEffect(() => {
        dispatch(searchProduct({ keywords, nextPage: 1, pageSize: 10 }))
    }, [location])

    const onPageChange = (nextPage, pageSize) => {
        dispatch(searchProduct({ keywords, nextPage, pageSize }))
    }

    if (loading) {
        return (
            <Spin
                size="large"
                style={{
                    marginTop: 200,
                    marginBottom: 200,
                    marginLeft: "auto",
                    marginRight: "auto",
                    width: "100%",
                }}
            />
        )
    }
    if(error){
        return <div>网站出错：{error}</div>
    }
    return <>
        <Header />
        <div className={styles["page-content"]}>
            <div className={"product-list-container"}>
                <FilterArea />
            </div>
            <div className={"product-list-container"}>
                <ProductList data={data}
                    paging={paging}
                    onPageChange={onPageChange}
                />
            </div>
        </div>
        <Footer />
    </>
}